package com.example.demo.config;

import com.example.demo.dao.PermissionRepository;
import com.example.demo.entity.Role;
import com.example.demo.entity.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

// localhost:8080/admin/hello
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
   // @Autowired
   PermissionRepository permissionRepository;
    CustomFilterInvocationSecurityMetadataSource(PermissionRepository permissionRepository){
        this.permissionRepository = permissionRepository;
    }
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();//admin/hello
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        List<Permission> urls = permissionRepository.findAll();/// admin/**   dba/**   user/**
        for (Permission url: urls){
            if(antPathMatcher.match(url.getName(),requestUrl)){
                List<Role> roles = url.getRoles();
                String [] rolestr = new String[roles.size()];
                for (int i = 0; i < roles.size(); i++) {
                    rolestr[i] = roles.get(i).getName();
                    System.out.println(rolestr[i]);
                }
                return SecurityConfig.createList(rolestr);//可以访问这个url的所有的角色
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
